#include "videoplayer.h"
#include <QDebug>

VideoPlayer::VideoPlayer(QWidget *parent)
    : QGraphicsView(parent),
    scene(nullptr),
    pixmapItem(nullptr)
{
    initScene();

    // 设置背景颜色
    setBackgroundBrush(Qt::black);

    // 设置渲染提示
    setRenderHint(QPainter::Antialiasing, false);
    setRenderHint(QPainter::SmoothPixmapTransform, true);

    // 启用缓存
    setCacheMode(QGraphicsView::CacheBackground);

    // 设置缩放模式
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorUnderMouse);

    // 设置滚动条策略
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
}

VideoPlayer::~VideoPlayer()
{
    if (scene) {
        delete scene;
    }
}

void VideoPlayer::initScene()
{
    // 创建场景
    scene = new QGraphicsScene(this);
    setScene(scene);

    // 创建图像项
    pixmapItem = new QGraphicsPixmapItem();
    pixmapItem->setTransformationMode(Qt::SmoothTransformation);
    scene->addItem(pixmapItem);

    // 初始化场景矩形
    updateSceneRect();
}

void VideoPlayer::displayFrame(const QImage &image)
{
    if (image.isNull())
        return;

    // 保存当前图像
    currentImage = image;

    // 更新场景
    QPixmap pixmap = QPixmap::fromImage(image);
    pixmapItem->setPixmap(pixmap);

    // 调整场景大小
    scene->setSceneRect(pixmap.rect());

    // 调整视图以适应内容
    fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
}

void VideoPlayer::resizeEvent(QResizeEvent *event)
{
    QGraphicsView::resizeEvent(event);
    // 调整视图以适应内容
    if (!currentImage.isNull()) {
        //fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
        fitInView(pixmapItem, Qt::IgnoreAspectRatio);
    }
}

void VideoPlayer::updateSceneRect()
{
    // 设置场景矩形
    scene->setSceneRect(0, 0, width(), height());
}
